package com.sise.foodplatform.controller;

import com.alibaba.fastjson.JSON;
import com.sise.foodplatform.pojo.Food;
import com.sise.foodplatform.pojo.QueryInfo;
import com.sise.foodplatform.service.FoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

@RestController
public class FoodController {
    @Autowired
    private FoodService foodService;

    @RequestMapping("/allFood")
    public String getFoodList(QueryInfo queryInfo){
        int numbers = foodService.getFoodCounts("%" + queryInfo.getQuery() + "%");
        int pageStart = (queryInfo.getPageNum() - 1) * queryInfo.getPageSize();
        List<Food> foods = foodService.getAllFood("%" + queryInfo.getQuery() + "%", pageStart, queryInfo.getPageSize());
        HashMap<String, Object> res = new HashMap<>();
        res.put("numbers",numbers);
        res.put("foods",foods);
        String res_string = JSON.toJSONString(res);
        return res_string;
    }

    @RequestMapping("/deleteFood")
    public String deleteFood(int id){
        int i = foodService.deleteFood(id);
        return i>0?"success":"error";
    }

    @RequestMapping("/addFood")
    public String addFood(@RequestBody Food food){
        food.setState(false);
        int i = foodService.addFood(food);
        return i>0?"success":"error";
    }

    @RequestMapping("/getUpdateFood")
    public String getUpdateFood(int id){
        Food food = foodService.getUpdateFood(id);
        String s = JSON.toJSONString(food);
        return s;
    }

    @RequestMapping("/editFood")
    public String editFood(@RequestBody Food food){
        int i = foodService.editFood(food);
        return i>0?"success":"error";
    }

    @RequestMapping("/getFoodByName")
    public String getFoodByName(QueryInfo queryInfo){
        int numbers = foodService.getCountsByName(queryInfo.getQuery());
        int pageStart = (queryInfo.getPageNum() - 1) * queryInfo.getPageSize();
        List<Food> foods = foodService.getFoodByName(queryInfo.getQuery(), pageStart, queryInfo.getPageSize());
        HashMap<String, Object> res = new HashMap<>();
        res.put("numbers",numbers);
        res.put("foods",foods);
        String res_string = JSON.toJSONString(res);
        return res_string;
    }

}
